#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Foxglove运行处理器
负责检测、安装和启动Foxglove应用程序
"""

import subprocess
from pathlib import Path
from PySide2.QtWidgets import QMessageBox
from PySide2.QtCore import QObject, Signal
from mooetoolapp.threadcore.runfoxglovethread import RunFoxgloveThread
from mooetoolapp.handlercore.language_manager import LanguageManager

try:
    from gglobal import logger
except ImportError:
    import logging
    logger = logging.getLogger(__name__)

class RunFoxgloveHandler(QObject):
    """Foxglove运行处理器类"""
    
    # 信号定义
    foxglove_status_changed = Signal(str)  # Foxglove状态变化信号
    installation_requested = Signal(str)   # 安装请求信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_widget = parent
        self.foxglove_installer_path = Path("resource/app/foxglove-latest-win.exe")
        
        # 初始化语言管理器
        self.language_manager = LanguageManager()
        
        # 初始化线程
        self.foxglove_thread = None
        
        # 连接信号
        self._connect_signals()
    
    def _connect_signals(self):
        """连接信号槽"""
        pass  # 信号连接将在线程创建时进行
        
    def handle_play_bag_clicked(self):
        """处理播放Bag按钮点击事件"""
        logger.info("开始处理播放Bag功能")
        
        try:
            # 如果线程正在运行，则不重复启动
            if self.foxglove_thread and self.foxglove_thread.isRunning():
                logger.info("Foxglove线程正在运行中")
                return
            
            # 创建并启动线程
            self.foxglove_thread = RunFoxgloveThread(
                installer_path=str(self.foxglove_installer_path),
                parent=self
            )
            
            # 连接线程信号
            self.foxglove_thread.status_updated.connect(self._on_status_updated)
            self.foxglove_thread.error_occurred.connect(self._on_error_occurred)
            self.foxglove_thread.installation_progress.connect(self._on_installation_progress)
            self.foxglove_thread.foxglove_started.connect(self._on_foxglove_started)
            self.foxglove_thread.foxglove_already_running.connect(self._on_foxglove_already_running)
            self.foxglove_thread.installation_requested.connect(self._on_installation_requested)
            
            # 启动线程
            self.foxglove_thread.start()
            
        except Exception as e:
            logger.error(f"处理播放Bag功能时出错: {e}")
            self._show_error_message(f"启动Foxglove时出错: {str(e)}")
    
    def _on_status_updated(self, status):
        """状态更新处理"""
        logger.info(f"Foxglove状态更新: {status}")
        self.foxglove_status_changed.emit(status)
    
    def _on_error_occurred(self, error_msg):
        """错误处理"""
        logger.error(f"Foxglove操作错误: {error_msg}")
        QMessageBox.critical(
            self.parent_widget,
            self.language_manager.get_text("foxglove_error_title", category="constants"),
            self.language_manager.get_text("foxglove_launch_error", category="constants").format(error=error_msg)
        )
    
    def _on_installation_progress(self, progress):
        """安装进度处理"""
        logger.info(f"安装进度: {progress}%")
    
    def _on_foxglove_started(self):
        """Foxglove启动成功处理"""
        logger.info("Foxglove启动成功")
        QMessageBox.information(
            self.parent_widget,
            self.language_manager.get_text("foxglove_success_title", category="constants"),
            self.language_manager.get_text("foxglove_success_message", category="constants")
        )
    
    def _on_foxglove_already_running(self):
        """Foxglove已运行处理"""
        logger.info("Foxglove已在运行中")
        QMessageBox.information(
            self.parent_widget,
            self.language_manager.get_text("foxglove_running_title", category="constants"),
            self.language_manager.get_text("foxglove_running_message", category="constants")
        )
    
    def _on_installation_requested(self, installer_path):
        """安装请求处理"""
        logger.info(f"请求安装Foxglove: {installer_path}")
        
        try:
            if not Path(installer_path).exists():
                logger.error(f"Foxglove安装程序不存在: {installer_path}")
                self._show_error_message(f"找不到Foxglove安装程序\n路径: {installer_path}")
                return
            
            # 询问用户是否要安装
            reply = QMessageBox.question(
                self.parent_widget,
                self.language_manager.get_text("foxglove_install_dialog_title", category="constants"),
                self.language_manager.get_text("foxglove_install_dialog_message", category="constants"),
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes
            )
            
            if reply == QMessageBox.Yes:
                logger.info(f"开始安装Foxglove: {installer_path}")
                
                # 启动安装程序 - Windows系统：添加CREATE_NO_WINDOW标志隐藏命令行窗口
                subprocess.Popen([installer_path], shell=True, creationflags=subprocess.CREATE_NO_WINDOW)
                
                # 发射安装请求信号
                self.installation_requested.emit(installer_path)
                
                QMessageBox.information(
                    self.parent_widget,
                    self.language_manager.get_text("foxglove_installing_title", category="constants"),
                    self.language_manager.get_text("foxglove_installing_message", category="constants")
                )
            
        except Exception as e:
            logger.error(f"处理安装请求时出错: {e}")
            QMessageBox.critical(
                self.parent_widget,
                self.language_manager.get_text("foxglove_error_title", category="constants"),
                self.language_manager.get_text("foxglove_install_error", category="constants").format(error=str(e))
            )
    
    # 移除重复的检测和启动方法，这些逻辑已合并到RunFoxgloveThread中
    
    def _show_foxglove_running_message(self):
        """显示Foxglove正在运行的消息"""
        QMessageBox.information(
            self.parent_widget,
            "Foxglove运行中",
            "Foxglove已在运行中，请检查任务栏或切换到Foxglove窗口。"
        )
    
    def _show_error_message(self, message):
        """显示错误消息"""
        QMessageBox.critical(
            self.parent_widget,
            "错误",
            message
        )
    
    def cleanup(self):
        """清理资源"""
        try:
            # 停止并清理线程
            if self.foxglove_thread and self.foxglove_thread.isRunning():
                logger.info("正在停止Foxglove线程...")
                self.foxglove_thread.quit()
                self.foxglove_thread.wait(3000)  # 等待最多3秒
                if self.foxglove_thread.isRunning():
                    logger.warning("强制终止Foxglove线程")
                    self.foxglove_thread.terminate()
                    self.foxglove_thread.wait(1000)
            
            self.foxglove_thread = None
            logger.info("RunFoxgloveHandler资源清理完成")
            
        except Exception as e:
            logger.error(f"清理RunFoxgloveHandler资源时出错: {e}")